#!/bin/sh

SRC_DIR=`dirname $0`
source $SRC_DIR/env.sh

TMP_DIR=$STATS_DIR/tmp
RES_LOCK_TIME=$STATS_DIR/lock_time
RES_STATS=$STATS_DIR/mongod_stats
mkdir -p $TMP_DIR

NSMAX=1200000

## 1. TIMELINE DB NAMESPACE USED
echo 'rs.slaveOk()
var index = db.timeline_index.find({s: {$lte :db.id_generator.findOne({n:"user"}).i}}).sort({s:-1})[0]
print(index.i.valueOf() + " " + (index.e - index.s).valueOf())' > $TMP_DIR/getuid.js

TIMELINE_ID_AND_MAX=`$MONGO --quiet localhost:27017/openfollow -u $PRCM_ID -p $PRCM_PASS $TMP_DIR/getuid.js`
TIMELINE_ID=`echo $TIMELINE_ID_AND_MAX | cut -d ' ' -f 1`
TIMELINE_MAX=`echo $TIMELINE_ID_AND_MAX | cut -d ' ' -f 2`

echo 'rs.slaveOk()
var size = db.system.namespaces.find().size()
print(size)' > $TMP_DIR/getsize.js
TIMELINE_SIZE=`$MONGO --quiet localhost:27017/openfollow-tl${TIMELINE_ID} -u $PRCM_ID -p $PRCM_PASS $TMP_DIR/getsize.js`
TIMELINE_USED=`echo "scale=4;(${TIMELINE_SIZE}/${NSMAX})*100" | bc`

echo "TIMELINE_USED	${TIMELINE_USED}" > $RES_STATS


## 2. GLOBAL LOCK TIME
if [ -f $RES_LOCK_TIME ]; then mv $RES_LOCK_TIME ${RES_LOCK_TIME}.previous; fi
echo 'var lock = db.serverStatus().globalLock
print(lock.lockTime + " " + lock.totalTime)' > $TMP_DIR/getlock.js
$MONGO --quiet localhost:27017/admin -u $ADMIN_ID -p $ADMIN_PASS $TMP_DIR/getlock.js > $RES_LOCK_TIME
if [ -f ${RES_LOCK_TIME}.previous ]; then
  LOCK_TIME_PREV=(`cat ${RES_LOCK_TIME}.previous`)
  LOCK_TIME=(`cat $RES_LOCK_TIME`)
  echo "LOCK_RATE	`echo "scale=6;((${LOCK_TIME[0]}-${LOCK_TIME_PREV[0]}) / (${LOCK_TIME[1]}-${LOCK_TIME_PREV[1]}))*100" | bc`" >> $RES_STATS
fi

  
